//
//  CZDoujinListViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/17.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZDoujinListViewController.h"
#import "CZWaterflowLayout.h"
#import "CZDoujinCell.h"
#import "CZDoujinDetailViewController.h"

static NSString *const doujin_cell = @"doujin_cell";

@interface CZDoujinListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, CZWaterflowLayoutDelegate>
@property (nonatomic, strong) NSMutableArray *doujinArray;
@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation CZDoujinListViewController

- (NSMutableArray *__nonnull)doujinArray {
    if (!_doujinArray) {
        _doujinArray = [[NSMutableArray alloc] init];
    }
    return _doujinArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//  创建布局
    [self postDoujinListDataWithType:self.type];
    _currentPage = 1;
    CZWaterflowLayout *layout = [[CZWaterflowLayout alloc] init];
    layout.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
//  创建CollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -64, Main_Screen_Width, Main_Screen_Height - 20) collectionViewLayout:layout];
    collectionView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:collectionView];
    
    [collectionView reloadData];

    _refreshView = [LGRefreshView refreshViewWithScrollView:collectionView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 _currentPage = 1;
                                                 self.doujinCollectionView.mj_footer.state = MJRefreshStateIdle;
                                                 [self postDoujinListDataWithType:self.type];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    // 注册
    [collectionView registerNib:[UINib nibWithNibName:@"CZDoujinCell" bundle:nil] forCellWithReuseIdentifier:doujin_cell];
    self.doujinCollectionView = collectionView;
    self.doujinCollectionView.mj_footer = [MJDIYBackFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self postDoujinListDataWithType:self.type];
    }];
}

- (void)loadMoreData {
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    self.doujinCollectionView.frame = self.layoutView.bounds;
}

#pragma mark- network
- (void)postDoujinListDataWithType:(NSNumber *)type {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/doujin-index",APP_HOST];
    [SVProgressHUD show];
    [GCZAFNetWorking POST:urlString params:@{@"type" : self.type, @"page": @(_currentPage)} success:^(NSDictionary *response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *array = response[@"result"];
            if (_currentPage == 1) {
//                self.doujinArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* obj1, NSDictionary* obj2) {
//                    
//                    NSString *number1 = obj1[@"doujin_id"];
//                    NSString *number2 = obj2[@"doujin_id"];
//                    NSComparisonResult result = [number1 compare:number2];
//                    return result == NSOrderedDescending; // 升序
//                }].mutableCopy;
                
                self.doujinArray = array.mutableCopy;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.doujinCollectionView reloadData];
                });
            } else {
                if (array.count < 1) {
                    [self.doujinCollectionView.mj_footer endRefreshing];
                    self.doujinCollectionView.mj_footer.state = MJRefreshStateNoMoreData;
                } else {
                    [self.doujinCollectionView.mj_footer endRefreshing];
                    for (NSDictionary *dic in array) {
                        [self.doujinArray addObject:dic];
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.doujinCollectionView reloadData];
                    });
                }
            }
            
        }
        [_refreshView endRefreshing];
        [self.doujinCollectionView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [_refreshView endRefreshing];
        [self.doujinCollectionView.mj_footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}


#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.doujinArray.count;
//    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CZDoujinCell *cell = (CZDoujinCell *)[collectionView dequeueReusableCellWithReuseIdentifier:doujin_cell forIndexPath:indexPath];
    NSDictionary *dic = self.doujinArray[indexPath.row];
    if (![dic[@"share_pics"] isKindOfClass:[NSNull class]]) {
        cell.doujinIcon.yy_imageURL = [NSURL URLWithString:[dic[@"share_pics"] stringByAppendingString:@"?x-oss-process=style/ios_doujin_50"]];
    }
    if (![dic[@"author"] isKindOfClass:[NSNull class]]) {
        cell.doujinAuthorLabel.text = dic[@"author"];
    }
    if (![dic[@"reward"] isKindOfClass:[NSNull class]]) {
        cell.doujinReward.text = dic[@"reward"];
    }
    cell.layer.contentsScale = [UIScreen mainScreen].scale;
    cell.layer.shadowOpacity = 0.3f;
    cell.layer.shadowRadius = 4.0f;
    cell.layer.shadowOffset = CGSizeMake(0,0);
    cell.layer.shadowPath = [UIBezierPath bezierPathWithRect:cell.bounds].CGPath;
    cell.layer.masksToBounds = NO;
    cell.backgroundColor = [UIColor whiteColor];
    
    //设置缓存
    cell.layer.shouldRasterize = YES;
    //设置抗锯齿边缘
    cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.doujinArray[indexPath.row];
    CZDoujinDetailViewController *detailVC = [[CZDoujinDetailViewController alloc] init];
    detailVC.dataDic = dic;
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark - <WaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(CZWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth {
    NSDictionary *dic = self.doujinArray[index];
    NSInteger pic_width = ((NSString *)dic[@"pic_width"]).integerValue;
    NSInteger pic_height = ((NSString *)dic[@"pic_height"]).integerValue;
    CGFloat scale = (CGFloat)pic_height / pic_width;
    DLog(@"width  = %d,  height = %d , scale = %.2f", pic_width, pic_height, scale);
    return (itemWidth - 20) * scale + 40;
}

- (CGFloat)rowMarginInWaterflowLayout:(CZWaterflowLayout *)waterflowLayout {
    return 10;
}

- (CGFloat)columnCountInWaterflowLayout:(CZWaterflowLayout *)waterflowLayout {
    return 2;
}

- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(CZWaterflowLayout *)waterflowLayout {
    return UIEdgeInsetsMake(10, 0, 30, 0);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
